package com.gsnd.briuppts.service.impl;

import com.gsnd.briuppts.Result.ResponseCode;
import com.gsnd.briuppts.Util.JwtUtil;
import com.gsnd.briuppts.entity.BaseAccount;
import com.gsnd.briuppts.entity.Do.BaseAccountExtend;
import com.gsnd.briuppts.entity.Do.BaseAuthorityExtend;
import com.gsnd.briuppts.entity.Do.LoginVo;
import com.gsnd.briuppts.exception.PtsException;
import com.gsnd.briuppts.mapper.BaseAccountMapper;
import com.gsnd.briuppts.mapper.BaseAuthorityMapper;
import com.gsnd.briuppts.service.BaseAccountService;
import com.gsnd.briuppts.service.BaseAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service //在service的实现类上必加
public class BaseAccountServiceImpl implements BaseAccountService {

    @Autowired  //自动注入
    BaseAccountMapper baseAccountMapper;
    @Autowired
    BaseAuthorityService baseAuthorityService;
    @Override
    public LoginVo login(String username, String password) {
        if("".equals(username)|| username==null){
            throw new PtsException(ResponseCode.DATA_EMPTY);
        }
        if("".equals(password) || password==null){
            throw new PtsException(ResponseCode.DATA_EMPTY);
        }
        BaseAccount baseAccount =baseAccountMapper.getAccountByUsernameAndPwd(username, password);
        if(baseAccount==null){
            throw new PtsException(ResponseCode.USER_NOT_EXISTED);
        }
        System.out.println(baseAccount);
        String id =baseAccount.getAccountId();
        String name= baseAccount.getUsername();
        Map<String,Object> info=new HashMap<>();
        info.put("username",name);
        String token = JwtUtil.sign(id, info);
        LoginVo loginVo=new LoginVo();
        loginVo.setAccountId(id);
        loginVo.setUsername(name);
        loginVo.setToken(token);
        return loginVo;
    }
    @Override
    public BaseAccount findByAccountId(String accountId) {
        return baseAccountMapper.getAccountById(accountId);
    }
    @Override
    public BaseAccountExtend findAccountAndRoleByAccountId(String accountId){
        BaseAccountExtend accountAndRole = baseAccountMapper.getAccountAndRoleByAccountId(accountId);
        List<BaseAuthorityExtend> authorities = baseAuthorityService.findAllAuthoritiesTree(accountId);
        accountAndRole.setAuthorities(authorities);
        return accountAndRole;
    }

}


